package com.dxg.msns.gateway.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;

/**
 * Token获取工具类
 * 支持从Authorization请求头和Cookie中获取JWT Token
 */
public class TokenUtils {
    private static final Logger logger = LoggerFactory.getLogger(TokenUtils.class);

    private static final String BEARER_PREFIX = "Bearer ";

    /**
     * 从请求中获取JWT Token
     * 优先级：Authorization请求头 > Cookie
     * 
     * @param request    HTTP请求
     * @param cookieName Cookie名称（用于备用方案）
     * @return JWT Token字符串，如果未找到返回null
     */
    public static String getTokenFromRequest(ServerHttpRequest request, String cookieName) {
        // 优先从 Authorization 请求头获取
        String token = getTokenFromAuthorizationHeader(request);
        if (token != null) {
            return token;
        }

        // 备用方案：从Cookie获取（保持向后兼容）
        token = getTokenFromCookie(request, cookieName);
        if (token != null) {
            logger.debug("Token found in Cookie as fallback");
            return token;
        }

        logger.debug("No token found in Authorization header or Cookie");
        return null;
    }

    /**
     * 从Authorization请求头获取Token
     * 支持格式：Authorization: Bearer <token>
     * 
     * @param request HTTP请求
     * @return JWT Token字符串，如果未找到返回null
     */
    public static String getTokenFromAuthorizationHeader(ServerHttpRequest request) {
        String authHeader = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (StringUtils.hasText(authHeader) && authHeader.startsWith(BEARER_PREFIX)) {
            String token = authHeader.substring(BEARER_PREFIX.length()).trim();
            if (StringUtils.hasText(token)) {
                logger.debug("Token found in Authorization header");
                return token;
            }
        }
        return null;
    }

    /**
     * 从Cookie获取Token
     * 
     * @param request    HTTP请求
     * @param cookieName Cookie名称
     * @return JWT Token字符串，如果未找到返回null
     */
    public static String getTokenFromCookie(ServerHttpRequest request, String cookieName) {
        if (!StringUtils.hasText(cookieName)) {
            return null;
        }

        return GatewayCookieUtils.getCookieValue(request, cookieName);
    }

    /**
     * 验证Token格式是否正确
     * 
     * @param token JWT Token
     * @return 是否为有效格式
     */
    public static boolean isValidTokenFormat(String token) {
        if (!StringUtils.hasText(token)) {
            return false;
        }

        // JWT Token通常包含两个点分隔的三部分
        String[] parts = token.split("\\.");
        return parts.length == 3;
    }
}